# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
import os, copy
from datetime import datetime
import base64
import StringIO
import xlwt
import sys
import jinja2

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_ext', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


class stock_picking(osv.osv):
    _inherit = 'stock.picking'

    def _get_address_by_order(self, order):
        if not order:
            return ''

        return (order.province_id and order.province_id.name or '') + (
            order.city_id and order.city_id.city_name or '') + (
            order.county_id and order.county_id.county_name or '') + (order.street or '')

    def _get_position_html(self, cr, uid, ids, field_name, arg, context=None):
        template = env.get_template('position.html')
        res = {}
        for picking in self.browse(cr, uid, ids, context=context):
            if picking.picking_type_id.code == 'outgoing':
                picking_position = template.render({'picking_id': picking.id, 'address': self._get_address_by_order(picking.so_id)})

                res.update({picking.id: picking_position})
            else:
                res.update({picking.id: ''})

        return res

    _columns = {
        'position_html': fields.function(_get_position_html, type='html', string=u'地理位置'),
        'delivery_user_id': fields.many2one('res.users', u'送货人', copy=False),
        'delivery_state': fields.selection([('waiting_delivery', u'待送货'), ('shipping', u'送货中'), ('delivery_done', u'送货完成')], u'送货状态', copy=False),
        'delivery_start_time': fields.datetime(u'开始送货时间'),
        'delivery_done_time': fields.datetime(u'送达时间'),
        'position_ids': fields.one2many('stock.position', 'picking_id', u'送货员地理信息', copy=False),
    }


class stock_position(osv.osv):
    _name = 'stock.position'
    _order = 'create_date desc'

    _columns = {
        'create_date': fields.datetime(u'创建时间'),
        'picking_id': fields.many2one('stock.picking', u'发货单'),
        'user_id': fields.many2one('res.users', u'送货人'),
        'latitude': fields.float(u'维度', digits=(14, 6)),
        'longitude': fields.float(u'经度', digits=(14, 6)),
        'speed': fields.float(u'速度', digits=(14, 6)),
        'accuracy': fields.float(u'精度'),
    }


class gps_position(osv.osv):
    _name = 'gps.position'

    _columns = {
        'vehicle': fields.char(u'车牌'),
        'gpstime': fields.datetime(u'GPS时间'),
        'speed': fields.float(u'速度', digits=(16, 2)),
        'odometer': fields.float(u'GPS里程', digits=(16, 3)),
        'lat': fields.float(u'维度', digits=(16, 6)),
        'lon': fields.float(u'经度', digits=(16, 6)),
        'direction': fields.float(u'方向（度）', digits=(16, 2)),
        'status': fields.char(u'GPS状态'),
        'placename': fields.char(u'车辆位置'),
        'waiting_time': fields.float(u'停车时间'),
    }


class dftg_stock_inventory_line(osv.osv):
    _inherit = 'stock.inventory.line'

    def _compute_inventory_cost(self, cr, uid, ids, name, args, context=None):
        res = {}
        quant_obj = self.pool.get('stock.quant')
        for line in self.browse(cr, uid, ids, context=context):
            quant_ids = self._get_quants(cr, uid, line, context=context)
            all_qty, all_cost = 0, 0
            for quant in quant_obj.browse(cr, uid, quant_ids, context=context):
                all_qty += quant.qty
                all_cost += quant.qty * quant.cost
            res[line.id] = all_qty and all_cost / all_qty
        return res
    _columns = {
        'quant_cost': fields.function(_compute_inventory_cost, string='成本单价',
                                      type='float', store=True),
    }

class dftg_stock_inventory(osv.osv):
    _inherit = 'stock.inventory'

    def print_inventory(self, cr, uid, ids, context=None):
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'export.stock.inventory.wizard',
            'view_mode': 'form',
            'view_type': 'form',
            'views': [(False, 'form')],
            'target': 'new',
        }


class export_stock_inventory_wizard(osv.osv_memory):
    _name = 'export.stock.inventory.wizard'
    _columns = {
        'filename': fields.char(u'文件名', readonly=1),
        'data': fields.binary(u'文件', readonly=1),
        'state': fields.selection([('1', '1'), ('2', '2')], string=u'状态'),
    }
    _defaults = {
        'state': '1',
    }

    def model_fields_data_provide(self, cr, uid, context=None):
        name_location = {
            'name': 6,
            'location_id': 2,
            'date': 2,
            'filter': 2,
            'period_id': 2,
            'line_ids_product_id': 2,
            'line_ids_location_id': 1,
            'line_ids_theoretical_qty': 1,
            'line_ids_product_qty': 1,
            'line_ids_quant_cost': 1,
        }
        field_str = {
            'location_id': '盘点库位',
            'date': '盘点日期',
            'filter': '盘点对',
            'period_id': '期间',
            'line_ids_product_id': '产品 ',
            'line_ids_location_id': '库位 ',
            'line_ids_theoretical_qty': '账面数量',
            'line_ids_product_qty': '实际数量',
            'line_ids_quant_cost': '成本单价',
        }
        field_val = {
            'location_id': 'name',
            'line_ids_location_id': 'display_name',
            'line_ids_product_id': 'display_name',
            'period_id': 'name',
            'line_ids': ['product_id', 'location_id', 'theoretical_qty', 'product_qty', 'quant_cost']
        }
        print_field = [
            ['name'],
            ['location_id', 'date'],
            ['filter', 'period_id'],
            ['line_ids']
        ]
        return name_location, field_val, print_field, field_str


    #导出确认
    def button_next(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if isinstance(ids, int):
            this_id = ids
        else:
            this_id = ids[0]
        xls = StringIO.StringIO()
        xls_workbook = xlwt.Workbook(encoding="utf8")
        data_sheet = xls_workbook.add_sheet('data', cell_overwrite_ok=True)
        selected = context.get('active_ids')
        name_location, field_val, print_field, field_str = self.model_fields_data_provide(cr, uid, context=context)
        model_row = self.pool.get(context.get('active_model')).browse(cr, uid, selected, context=context)
        row = 0
        for fields in print_field:
            col = 0
            for field in fields:
                if row == 0:
                    export_value = model_row[field]
                    self.write_merge(data_sheet, row, col, col + name_location.get(field), export_value)
                    col += name_location.get(field)
                else:
                    if isinstance(model_row[field], (int, float, basestring, str, bool)):
                        export_value = model_row[field]
                        self.write_merge(data_sheet, row, col, col+1, field_str.get(field))
                        col += 1
                        self.write_merge(data_sheet, row, col, col + name_location.get(field), export_value)
                        col += name_location.get(field)
                    elif isinstance(model_row[field], object) and not isinstance(field_val.get(field), list):
                        export_value = model_row[field][field_val.get(field)]
                        self.write_merge(data_sheet, row, col, col + 1, field_str.get(field))
                        col += 1
                        self.write_merge(data_sheet, row, col, col + name_location.get(field), export_value)
                        col += name_location.get(field)
                    else:
                        col = 0
                        for local_field in field_val.get(field):
                            self.write_merge(data_sheet, row, col, col + name_location.get('%s_%s' % (field, local_field)),
                                                   field_str.get('%s_%s' % (field, local_field)))
                            col += name_location.get('%s_%s' % (field, local_field))
                        col = 0
                        row += 1
                        for line in model_row[field]:
                            for local_field in field_val.get(field):
                                if local_field == 'location_id':
                                    print local_field
                                if isinstance(line[local_field], (int, float, basestring, str, bool)):
                                    self.write_merge(data_sheet, row, col,
                                                           col + name_location.get('%s_%s' % (field, local_field)), line[local_field])
                                elif isinstance(line[local_field], object) and not isinstance(field_val.get('%s_%s' % (field, local_field)), list):
                                    self.write_merge(data_sheet, row, col,
                                                           col + name_location.get('%s_%s' % (field, local_field)),
                                                           line[local_field][field_val.get('%s_%s' % (field, local_field))])

                                col += name_location.get('%s_%s' % (field, local_field))
                            row += 1
                            col = 0
            row += 1
        xls_workbook.save(xls)
        xls.seek(0)
        out = base64.encodestring(xls.getvalue())
        return self.return_vals_construction(cr, uid, this_id, out, context=context)

    def write_merge(self, data_sheet, row, col, col_locaiton, val):
        if col_locaiton - col == 1:
            data_sheet.write(row, col, val)
        else:
            data_sheet.merge(row, row, col, col_locaiton - 1)
            data_sheet.write(row, col, val)

    def return_vals_construction(self, cr, uid, ids, out, context=None):
        vals = {'data': out,
                'filename': u'下载盘点单%s.xls' % datetime.now().strftime("%Y%m%d"),
                'state': '2'}
        self.write(cr, uid, ids, vals, context=context)
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'export.stock.inventory.wizard',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': ids,
            'views': [(False, 'form')],
            'target': 'new',
        }
